<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */
namespace Admin\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Paginator\Paginator;
use Zend\Db\Sql\Select;
use Zend\Paginator\Adapter\Iterator as paginatorIterator;
use Application\Model\Product;
use Admin\Form\MenuForm;
use Admin\Form\NewsForm;
use Application\Model\vn3dUtil;
use Admin\Form\ProductForm;
use Zend\Session\Container;
use ZF2FileUploadExamples\Form;
use Application\Model\Image;
use Zend\Json\Json;

class ProductController extends AbstractActionController
{

    protected $ProductTable;
    protected $ImageTable;

    protected $path;

    protected $sessionContainer;
    protected $CategoryTable;


    public function __construct()
    {
        $this->path = $_SERVER['DOCUMENT_ROOT'] . 'product';
        $this->sessionContainer = new Container('file_upload_examples');
    }


    public function getCategoryTable()
    {
    	if (! $this->CategoryTable) {
    		$sm = $this->getServiceLocator();
    		$this->CategoryTable = $sm->get('Application\Model\CategoryTable');
    	}
    	return $this->CategoryTable;
    }
    public function getProductTable()
    {
        if (! $this->ProductTable) {
            $sm = $this->getServiceLocator();
            $this->ProductTable = $sm->get('Application\Model\ProductTable');
        }
        return $this->ProductTable;
    }
    public function getImageTable()
    {
        if (! $this->ImageTable) {
            $sm = $this->getServiceLocator();
            $this->ImageTable = $sm->get('Application\Model\ImageTable');
        }
        return $this->ImageTable;
    }

    public function indexAction()
    {if(!vn3dUtil::checkAuth(($this))){

        	return $this->redirect()->toRoute('user',array("action"=>"index"));
        };
        $groupProductID = $this->getEvent()
            ->getRouteMatch()
            ->getParam("id");
        $menuId=$this->getCategoryTable()->getCategorybyId($groupProductID)->parent_id;
        $order_by = $this->params()->fromRoute('order_by') ? $this->params()->fromRoute('order_by') : 'id';
        $order = $this->params()->fromRoute('order') ? $this->params()->fromRoute('order') : Select::ORDER_ASCENDING;
        $page = $this->params()->fromRoute('page') ? (int) $this->params()->fromRoute('page') : 1;
        // grab the paginator from the AlbumTable
        $paginator = $this->getProductTable()->fetchByGroupProductID($groupProductID, true,$order_by,$order);
        // set the current page to what has been passed in query string, or to 1 if none set
        $paginator->setCurrentPageNumber((int) $this->params()
            ->fromQuery('page', $page));
        // set the number of items per page to 10
        $paginator->setItemCountPerPage(5);

        $this->setLayoutAdmin($this);
        return new ViewModel(array(
            'order_by' => $order_by,
            'order' => $order,
            'page' => $page,
            'paginator' => $paginator,
            "groupProductID" => $groupProductID,
            "menuId"=>$menuId
        ));
    }

    public function addAction()
    {if(!vn3dUtil::checkAuth(($this))){

        	return $this->redirect()->toRoute('user',array("action"=>"index"));
        };

        $groupProductID = $this->getEvent ()->getRouteMatch ()->getParam ( "id" );
        $path = $this->path;
        $form = new ProductForm("product");
        $tempFile = null;
//         var_dump("post");
        $request = $this->getRequest();
//         var_dump($this->getRequest()->isPost());
//         var_dump($this->getRequest()->isGet());
        $product=new Product();
        if ($this->getRequest()->isPost()) {

//             $prg = $this->fileprg($form);

//             if ($prg instanceof \Zend\Http\PhpEnvironment\Response) {
//                 return $prg; // Return PRG redirect response
//             } elseif (is_array($prg)) {
            $data = array_merge_recursive ( $request->getPost ()->toArray (), $request->getFiles ()->toArray () );
            $form->setInputFilter($product->getInputFilter());
            $form->setData($data);
                if ($form->isValid()) {
                    $data = $form->getData();
//                     var_dump($data);

                    $product->name = $data['name'];
                    $product->desc = $data['desc'];
                    $product->short_desc = $data['short_desc'];
                    $product->price = $data['price'];
                    $product->code = $data['code'];
                    $product->category_id = $groupProductID;
                    $product->banner = file_get_contents($data['banner']['tmp_name']);
                    $product->banner_name = $data['banner']['name'];
                    $product->banner_size = $data['banner']['size'];
                    $product->banner_type = $data['banner']['type'];
                    $product->video = $data['video'];
                    $product->product_file = file_get_contents($data['product_file']['tmp_name']);
                    $product->product_file_name = $data['product_file']['name'];
                    $product->product_file_size = $data['product_file']['size'];
                    $product->product_file_type = $data['product_file']['type'];
                    // -------------
                    // $location->exchangeArray($request->getPost());
                   $productID= $this->getProductTable()->saveProduct($product);

                    $images=$data['image'];

                    foreach ($images as $key => $img) {
                        $image=new Image();
                        $image->content=file_get_contents($img['tmp_name']);
                        $image->name=$img['name'];
                        $image->type=$img['type'];
                        $image->size=$img['size'];
                        $image->product_id=$productID;
                    	$this->getImageTable()->saveImage($image);
                    }
//                     Redirect to list of albums
                    return $this->redirect()->toRoute('product', array(
                    		"action" => "index",
                            "id"=>"".$groupProductID
                    ));

                } else {
                    // Form not valid, but file uploads might be valid...
                    // Get the temporary file information to show the user in the view
                    $fileErrors = $form->get('banner')->getMessages();
                    if (empty($fileErrors)) {
                        $tempFile = $form->get('banner')->getValue();
                    }
                }
//             }


        }
        $this->setLayoutAdmin($this);
        return array(
            'form' => $form,
            'tempFile' => $tempFile,
            "groupProductID"=>$groupProductID

        );
    }
    public function editAction()
    {
        if(!vn3dUtil::checkAuth(($this))){

        	return $this->redirect()->toRoute('user',array("action"=>"index"));
        };
        $groupProductID = $this->getEvent ()->getRouteMatch ()->getParam ( "urlseo" );
        $productID = $this->getEvent ()->getRouteMatch ()->getParam ( "id" );

        $form = new ProductForm("product");
        $tempFile = null;
//         var_dump("post");
        $request = $this->getRequest();
//         var_dump($this->getRequest()->isPost());
//         var_dump($this->getRequest()->isGet());
        $product=new Product();
        if ($this->getRequest()->isPost()) {

//             $prg = $this->fileprg($form);

//             if ($prg instanceof \Zend\Http\PhpEnvironment\Response) {
//                 return $prg; // Return PRG redirect response
//             } elseif (is_array($prg)) {
            $data = array_merge_recursive ( $request->getPost ()->toArray (), $request->getFiles ()->toArray () );
            $form->setInputFilter($product->getInputFilter());
            $form->setData($data);
                if ($form->isValid()) {
                    $data = $form->getData();
//                     var_dump($data);

                $product->id = $productID;
                $product->name = $data['name'];
                    $product->desc = $data['desc'];
                    $product->short_desc = $data['short_desc'];
                    $product->price = $data['price'];
                    $product->code = $data['code'];
                    $product->category_id = $groupProductID;
                    if(!empty($data['banner']['tmp_name'])){
                    $product->banner = file_get_contents($data['banner']['tmp_name']);
                }
                    $product->banner_name = $data['banner']['name'];
                    $product->banner_size = $data['banner']['size'];
                    $product->banner_type = $data['banner']['type'];
                    $product->video = $data['video'];
                    if(!empty($data['product_file']['tmp_name'])){
                    $product->product_file = file_get_contents($data['product_file']['tmp_name']);
                    }

                    $product->product_file_name = $data['product_file']['name'];
                    $product->product_file_size = $data['product_file']['size'];
                    $product->product_file_type = $data['product_file']['type'];
                    // -------------
                    // $location->exchangeArray($request->getPost());
                   $this->getProductTable()->saveProduct($product);

                    $images=$data['image'];
//                     var_dump($images);
if(count($images)>1){
                    foreach ($images as $key => $img) {
                        $image=new Image();
                        $image->content=file_get_contents($img['tmp_name']);
                        $image->name=$img['name'];
                        $image->type=$img['type'];
                        $image->size=$img['size'];
                        $image->product_id=$productID;
                    	$this->getImageTable()->saveImage($image);
                    }
}
//                     Redirect to list of albums
                    return $this->redirect()->toRoute('product', array(
                    		"action" => "index",
                            "id"=>"".$groupProductID
                    ));

                } else {
                    // Form not valid, but file uploads might be valid...
                    // Get the temporary file information to show the user in the view
                    $fileErrors = $form->get('banner')->getMessages();
                    if (empty($fileErrors)) {
                        $tempFile = $form->get('banner')->getValue();
                    }
                }
//             }


        }
        $this->setLayoutAdmin($this);
        return array(
            'form' => $form,
            'tempFile' => $tempFile,
            "groupProductID"=>$groupProductID,
            "groupProduct"=>$this->getCategoryTable()->getCategorybyId($groupProductID),
            "menu"=>$this->getCategoryTable()->getTree(),
            "product"=>$this->getProductTable()->getProductbyId($productID),
            "productID"=>$productID,
            "images"=>$this->getImageTable()->getImageByProductId($productID)

        );
    }
    public function deleteImageAction(){
        if(!vn3dUtil::checkAuth(($this))){

        	return $this->redirect()->toRoute('user',array("action"=>"index"));
        };
        $this->layout("layout/ajax");
        header ( "Content-Type:application/json" );
        if ($this->getRequest ()->isPost ()) {
        	$imageID = $this->getRequest ()->getPost ( "image" );
        	$status=$this->getImageTable()->deleteImage($imageID);
        }
        echo Json::encode($status);
        return $this->getResponse();
    }
    public function deleteAction()
    {if(!vn3dUtil::checkAuth(($this))){

        	return $this->redirect()->toRoute('user',array("action"=>"index"));
        };
    	$id = (int) $this->params()->fromRoute('id', 0);
    	$groupProductID=(int) $this->params()->fromRoute('urlseo', 0);
    	if (! $id) {
    		return $this->redirect()->toRoute('product', array(
    				"action" => "index",
    		    "id"=>$groupProductID
    		));
    	}
    	$this->getProductTable()->deleteProduct($id);
    	return $this->redirect()->toRoute('product', array(
    			"action" => "index",
    		    "id"=>$groupProductID
    	));

    	return array(
    			'id' => $id
    	);
    }
    function after($parten, $inthat)
    {
        if (! is_bool(strpos($inthat, $parten)))
            return substr($inthat, strpos($inthat, $parten) + strlen($parten));
    }

    function strrevpos($instr, $needle)
    {
        $rev_pos = strpos(strrev($instr), strrev($needle));
        if ($rev_pos === false)
            return false;
        else
            return strlen($instr) - $rev_pos - strlen($needle);
    }

    function after_last($parten, $inthat)
    {
        if (! is_bool($this->strrevpos($inthat, $parten)))
            return substr($inthat, $this->strrevpos($inthat, $parten) + strlen($parten));
    }

    private function  setLayoutAdmin($controller){
    	$controller->layout("/layout/admin");
    	$controller->forward()->dispatch("Application\Controller\Store", array(
    			'action' => 'search',
    			'controller' => 'Application\Controller\Store'
    	));
    }
}
